#!/usr/local/bin/perl

#This is a simple lazy video downloader to mp4
#Sorry for the lazy code it was done during a 1 hour break

use strict;
use LWP::Simple;
use Data::Dumper;

#Getting the url
my $youtube_video_url = shift;

sub cleanDownloadUrl() {
	my $url = $_[0];
	$url =~ s/^=url%3D//g;
	$url =~ s/%253A/:/g;
	$url =~ s/%252F/\//g;
	$url =~ s/%253F/?/g;
	$url =~ s/(%253D|%3D)/=/g;
	$url =~ s/(%2526|%26)/&/g;
	$url =~ s/%25252C/,/g;
	$url =~ s/;//g;
	$url =~ s/'//g;
	$url =~ s/&$//g;
	return $url;
}


sub helpMe {
	print "******************************************************************\n";
	print "*  Youtube to MP4 downloader,   Iqbal Addou                      *\n";
	print "*  http://www.iqbaladdou.com  (iqbal.addou\@gmail.com)            *\n";
	print "*  Licenses: MIT License (MIT) , yt2mp4 v1.0 MAY/07/2012         *\n";
	print "******************************************************************\n";
	print "Usage: perl yt2mp4.pl [youtube url]\n\n\n";
}

unless($youtube_video_url =~ m/^http\:\/\/www\.youtube\.com\/watch\?v\=(.*)$/ && !($youtube_video_url =~ m/( |\t)/))
	{ 
		helpMe();
		die("ERROR: Please check your youtube url\n\n\n");
	}

eval {
	my $youtube_html_page_contents;
		
	#Getting the youtube html page content
	$youtube_html_page_contents = get($youtube_video_url);

	#Finding the mp4 download link
	my @video_ids = split(/&/,$youtube_video_url);
	my $video_id = $video_ids[0];
	$video_id =~ m/(v\=)([a-zA-Z0-9]+)(&|$)/g;
	$video_id = $2; 

	print "extracting video id = ".$video_id."\n"; 

	my @contents_array = split (/\n/, $youtube_html_page_contents);
	my @urls_array =   grep(/(o-o.preferred)/, @contents_array); 
		 
	my $url_str = $urls_array[1];

	my @contents3 = split(/url_encoded_fmt_stream_map/,$url_str);
	my @contents4 = split(/fallback_host/, $contents3[1]);

	#Cleaning the download link url
	my $url_tmp = @contents4[0];
	$url_tmp = &cleanDownloadUrl($url_tmp);
		 
	#The actual download
	$url_tmp = $url_tmp."&type=video/mp4";
	my $file = 'youtube_extract_vid_'."$video_id.mp4";
	use LWP::Simple qw($ua getstore);
	$ua->show_progress(1);
	getstore($url_tmp, $file);
};
if ($@) {
	die("Error downloading stream\n");
}

 
1;
 


